package cn.com.winning.ecare.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import yxt.push.org.androidpn.client.Notifier;
import yxt.push.org.androidpn.client.ServiceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.DeleteDirectory;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.model.MemberBaseInfo;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;

/**
 * 登入页面
 * 
 * @author Administrator
 */
public class Login extends Activity
{

	private Login oThis = this;
	private EditText etusername;
	private EditText etpassword;
	private PopupWindow popup;
	private Button loginButton, left, right;
	private ProgressDialog proDialog;
	private UpdateManager updateManager;
	private TextView tv;
	private TextView registertv;
	private ImageView registerview;
	EditText setIP;
	Button setIP_confirm, setIP_test, setIP_cancel;
	Dialog builder;
	private int windowwidth, windowheight;
	String mSavePath;

	String[] history = { "", "", "", "", "" };

	InputMethodManager manager;
	private AlertDialog outdialog;

	private SharedPreferences sharedPreferences;

	public ServiceManager serviceManager;
	private String versionName;
	MyApplication myApplication;

	 @SuppressLint("NewApi")
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
				.detectNetwork() // or .detectAll() for all detectable problems
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog()
				.penaltyDeath().build());
		setContentView(R.layout.login);
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		windowwidth = (int) (display.getWidth());
		windowheight = (int) (display.getHeight());
		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		// 生成视图
		findViews();

		// 获取IP缓存设置到URLUtils.Host
		setHost();

		// 设置登录、取消、历史记录按钮监听器
		setListener();
		// Start the service

		// 显示上次成功登入的用户名及密码
		initHis();

		updateManager = new UpdateManager(Login.this);
		// 获取当前软件版本
		versionName = updateManager.findVersionName();
		// 检查软件更新
		updateManager.checkUpdate(0);

		checkDir();

	}

	private void checkDir()
	{
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{
			// 获得存储卡的路径
			String sdpath = Environment.getExternalStorageDirectory() + "/";
			mSavePath = sdpath + "download";

		}
		else
		{
			mSavePath = getDir("download", Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE)
					.toString();
		}
		DeleteDirectory.getDeleteDirectory().deleteSDCardFolder(new File(mSavePath));
	}

	public static OnFocusChangeListener onFocusAutoClearHintListener = new OnFocusChangeListener()
	{
		@Override
		public void onFocusChange(View v, boolean hasFocus)
		{
			EditText textView = (EditText) v;
			String hint;
			if (hasFocus)
			{
				hint = textView.getHint().toString();
				textView.setTag(hint);
				textView.setHint("");
			}
			else
			{
				hint = textView.getTag().toString();
				textView.setHint(hint);
			}
		}
	};

	private void initHis()
	{
		// 获取登录信息
		List<MemberBaseInfo> MemberBaseInfos = getSPMembers();
		if (MemberBaseInfos != null && MemberBaseInfos.size() > 0)
		{
			MemberBaseInfo info = MemberBaseInfos.get(0);
			info.getName();
			info.getPassword();
			etusername.setText(info.getName().toString().trim());
			etpassword.setText(info.getPassword().toString().trim());
		}

	}

	// 保存用户信息
	private void saveSPMember(String memberName, String memberPwd)
	{
		// 获取登录信息
		List<MemberBaseInfo> MemberBaseInfos = getSPMembers();
		if (null == MemberBaseInfos)
			MemberBaseInfos = new ArrayList<MemberBaseInfo>();
		MemberBaseInfos = checkUser(MemberBaseInfos, memberName, memberPwd);// 检查是否已存在相同用户信息
		String userinfos = "";
		// 最终保存的用户信息都在list中
		for (MemberBaseInfo user : MemberBaseInfos)
		{
			String uName = user.getName();
			String uPwd = user.getPassword();
			String userinfo = uName + "/" + uPwd;
			if (userinfos == "")
			{
				userinfos = userinfo;
			}
			else
			{
				userinfos += "," + userinfo;
			}
		}
		SharedPreferences sharedPreferences = getSharedPreferences("userInfo", 0);
		Editor editor = sharedPreferences.edit();// 编辑器记录
		editor.putString("members", userinfos);
		editor.commit();// 编辑器提交保存
	}

	// 检查是否包含此用户名 没有包含就保存到?
	public List<MemberBaseInfo> checkUser(List<MemberBaseInfo> MemberBaseInfos, String memberName, String memberPwd)
	{
		if (null != MemberBaseInfos && MemberBaseInfos.size() > 0)
		{
			// 保证只有5条记录
			if (MemberBaseInfos.size() > 5)
			{
				for (int i = MemberBaseInfos.size() - 1; i > 4; i--)
				{
					MemberBaseInfos.remove(i);
				}
			}
			int position = 0;
			boolean isLoacate = false;
			for (int i = 0; i < MemberBaseInfos.size(); i++)
			{
				if (MemberBaseInfos.get(i).getName().equals(memberName))
				{
					position = i;
					isLoacate = true;
					break;
				}
			}
			if (isLoacate)
			{// 已存在
				MemberBaseInfos.remove(position);
			}
		}
		MemberBaseInfo memberBaseInfo = new MemberBaseInfo();
		memberBaseInfo.setName(memberName);
		memberBaseInfo.setPassword(memberPwd);

		MemberBaseInfos.add(0, memberBaseInfo);
		return MemberBaseInfos;
	}

	// 初始化保存的用户列表
	private void initHistoryList()
	{
		// 获取历史数据
		final List<MemberBaseInfo> MemberBaseInfos = getSPMembers();
		LayoutInflater mLayoutInflater = (LayoutInflater) Login.this.getSystemService(LAYOUT_INFLATER_SERVICE);
		ScrollView scrollView = (ScrollView) mLayoutInflater.inflate(R.layout.username_history, null);
		LinearLayout layout = (LinearLayout) scrollView.findViewById(R.id.layout);

		Resources resources = getResources();
		float with = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, resources.getDisplayMetrics());
		float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, resources.getDisplayMetrics());
		if (null != MemberBaseInfos)
		{
			final int count = MemberBaseInfos.size();
			for (int i = 0; i < count; i++)
			{
				final TextView text = new TextView(Login.this);
				text.setWidth(Math.round(with));
				text.setHeight(Math.round(height));
				text.setTextColor(Color.BLACK);
				text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
				text.setText(MemberBaseInfos.get(i).getName());

				text.setOnClickListener(new View.OnClickListener()
				{

					public void onClick(View v)
					{
						int position = 0;
						// 获取 当前MemberBaseInfo
						for (int i = 0; i < count; i++)
						{
							if (MemberBaseInfos.get(i).getName().toString().trim() == text.getText().toString().trim())
							{
								position = i;
								break;
							}
						}
						final MemberBaseInfo member = MemberBaseInfos.get(position);

						etusername.setText(text.getText());
						etusername.setSelection(etusername.length());

						etpassword.setText(member.getPassword().toString().trim());
						popup.dismiss();
					}
				});

				layout.addView(text);
			}
		}
		popup = new PopupWindow(scrollView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popup.update();
	}

	// 得到用户信息
	public List<MemberBaseInfo> getSPMembers()
	{
		List<MemberBaseInfo> memberBaseInfos = new ArrayList<MemberBaseInfo>();// 用于保存用户列表信息
		SharedPreferences sharedPreferences = getSharedPreferences("userInfo", 0);
		String userinfos = sharedPreferences.getString("members", "");// 取得所有用户信息
		// 获得用户字串
		if (!userinfos.equals(""))// 有数据
		{
			// name1/pwd1/true/false,name2/pwd2
			if (userinfos.contains(","))// 判断有无, 逗号代表用户每个用户分割点
			{
				String[] users = userinfos.split(",");
				for (String str : users)
				{
					MemberBaseInfo memberBaseInfo = new MemberBaseInfo();
					String[] user = str.split("/");
					memberBaseInfo.setName(user[0]);// 用户名
					memberBaseInfo.setPassword(user[1]);// 密码
					memberBaseInfos.add(memberBaseInfo);
				}
				return memberBaseInfos;
			}
			else
			// 没有, 代表只有一个用户
			{
				MemberBaseInfo memberBaseInfo = new MemberBaseInfo();
				String[] user = userinfos.split("/");
				memberBaseInfo.setName(user[0]);// 用户名
				memberBaseInfo.setPassword(user[1]);// 密码
				memberBaseInfos.add(memberBaseInfo);
				return memberBaseInfos;
			}
			// return memberBaseInfos;
		}
		else
		{
			return null;
		}
	}

	// 按钮的监听事件
	private void setListener()
	{
		// 用户名修改时,密码框清空内容
		etusername.addTextChangedListener(new TextWatcher()
		{

			@Override
			public void afterTextChanged(Editable arg0)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				// TODO Auto-generated method stub
				etpassword.setText("");
				if (etusername.getText().length() > 0)
				{
					etusername.setError(null);
				}

			}
		});

		loginButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				login();
			}
		});

	
		tv.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				tv.setTextColor(Color.RED);
				Intent intent = new Intent();
				intent.setClass(Login.this, Findpassword.class);
				startActivity(intent);
			}
		});
		registertv.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				registertv.setTextColor(Color.RED);
				Intent intent = new Intent();
				intent.setClass(Login.this, Register.class);
				startActivity(intent);
			}
		});
		registerview.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View v)
			{
				registertv.setTextColor(Color.RED);
				Intent intent = new Intent();
				intent.setClass(Login.this, Register.class);
				startActivity(intent);
			}
		});
	}

	// 登录
	public void login()
	{
		if (etusername.getText().toString().trim().equals(""))
		{
			int ecolor = Color.RED; // whatever color you want
			ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
			String estring = "用户名不能为空！";
			SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
			ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
			etusername.setError(ssbuilder);
			return;
		}

		else
		{
			proDialog = ProgressDialog.show(Login.this, "", "登录中...", true, true);
			Thread login = new LoginThread();
			login.start();
		}
	}

	// 开启一个线程类
	private class LoginThread extends Thread
	{
		// 将登录不成功的消息传递到UI线程
		private void loginUnSuccess(String msg)
		{
			proDialog.dismiss();
			// clearPreferences();
			Message message = new Message();
			Bundle bundle = new Bundle();
			bundle.putInt("type", 0);
			bundle.putString("msg", msg);
			message.setData(bundle);
			UIHandler.sendMessage(message);
		}

		@Override
		public void run()
		{
			String username = etusername.getText().toString().trim();
			String password = etpassword.getText().toString().trim();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("userid", username));
			params.add(new BasicNameValuePair("password", password));
			JSONObject res = HTTPGetTool.getTool().post(URLUtils.HOSTMAIN + URLUtils.URLLOGIN, params);
			try
			{
				if (res == null)
				{
					loginUnSuccess("连接服务器失败");
				}
				else if (res.get("loginInfo").equals("LOGIN_USERNOTEXIST"))
				{
					loginUnSuccess("用户名不存在");
				}
				else if (res.get("loginInfo").equals("LOGIN_PASSWORD_ERROR"))
				{
					loginUnSuccess("密码错误,请注意大小写");
				}
				else if (res.get("loginInfo").equals("LOGIN_NOTSUCCESS"))
				{
					loginUnSuccess("登录不成功");
				}
				else
				{
					// 记录登录信息
					String uName = etusername.getText().toString();
					String uPsw = etpassword.getText().toString();

					saveSPMember(uName, uPsw);

					MyApplication myApplication = (MyApplication) getApplication();
					myApplication.setAccount(username);
					myApplication.setVersion(versionName);
					myApplication.setUserName(uName);
					myApplication.setPassword(uPsw);
					// 主菜单配置信息传递到下一页面
					Intent intent = new Intent();
					JSONArray items = new JSONArray(res.getString("userinfo"));
					for (int j = 0; j < items.length(); j++)
					{
						JSONObject jobj = items.getJSONObject(j);
						myApplication.setDevicenumber(jobj.getString("devicenumber"));
						myApplication.setSfzh("");
						myApplication.setSjh(jobj.getString("sjh"));
						myApplication.setSex("");
						myApplication.setHzxm("");
					}
					intent.setClass(Login.this, HospitalChoice.class);

					startActivity(intent);

					proDialog.dismiss();
				}
			}
			catch (JSONException e)
			{
				// loginUnSuccess(e.toString());
			}
		}
	}

	// 处理不成功传回来的消息
	Handler UIHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			int type = msg.getData().getInt("type");
			switch (type)
			{
				case 0:
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
					builder.setMessage(msg.getData().getString("msg")).setCancelable(false)
							.setPositiveButton("确定", new DialogInterface.OnClickListener()
							{
								public void onClick(DialogInterface dialog, int id)
								{
									dialog.cancel();
								}
							});
					AlertDialog alert = builder.create();
					alert.show();
					break;
				}
				default:
				{}
			}
		}
	};

	// 初始化控件
	private void findViews()
	{
		etusername = (EditText) findViewById(R.id.username);
		etpassword = (EditText) findViewById(R.id.password);
		loginButton = (Button) findViewById(R.id.login_button);
		// historylist = (ImageButton) findViewById(R.id.history_username);
		registerview = (ImageView) findViewById(R.id.registerview);
		registerview.setClickable(true);
		tv = (TextView) findViewById(R.id.findpw);
		tv.setClickable(false);

		String htmlLinkText = "<a href=\"测试\">忘记密码?</a>";
		// 文字的样式（style）被覆盖，不能改变……
		tv.setText(Html.fromHtml(htmlLinkText));
		tv.setMovementMethod(LinkMovementMethod.getInstance());
		// tv.setTextColor(Color.RED);

		registertv = (TextView) findViewById(R.id.register_button);
		registertv.setClickable(false);

		String htmlLinkText2 = "<a href=\"测试\">还没有账号?现在注册</a>";
		// 文字的样式（style）被覆盖，不能改变……
		registertv.setText(Html.fromHtml(htmlLinkText2));
		registertv.setMovementMethod(LinkMovementMethod.getInstance());
		// registertv.setTextColor(Color.RED);

		etusername.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
		etpassword.setOnFocusChangeListener(this.onFocusAutoClearHintListener);
	}

	// 管理员帐号配置IP及端口
	private void setIPandPort()
	{
		LayoutInflater inflater = getLayoutInflater();
		View linearlayout = inflater.inflate(R.layout.setip, null);

		setIP = (EditText) linearlayout.findViewById(R.id.et_setIP);
		setIP_confirm = (Button) linearlayout.findViewById(R.id.setIP_confirm);
		setIP_test = (Button) linearlayout.findViewById(R.id.setIP_test);
		setIP_cancel = (Button) linearlayout.findViewById(R.id.setIP_cancel);

		setIP.setText(URLUtils.HOSTMAIN);

		builder = new AlertDialog.Builder(this)
		// .setIcon(R.drawable.srtm)
				.setTitle("服务器IP及端口号").setView(linearlayout).show();

		setIP_confirm.setOnClickListener(confirm);
		setIP_test.setOnClickListener(test);
		setIP_cancel.setOnClickListener(cancel);
	}

	// 事件 --确认
	private Button.OnClickListener confirm = new Button.OnClickListener()
	{

		public void onClick(View v)
		{
			// TODO Auto-generated method stub
			String hostip = setIP.getText().toString();
			URLUtils.HOSTMAIN = hostip;
			SharedPreferences sp = getSharedPreferences("mobile_ecare", 0);
			Editor et = sp.edit();
			et.putString("host", hostip);
			et.commit();
			Toast.makeText(Login.this, "成功设置服务器IP", Toast.LENGTH_SHORT).show();
			etpassword.setText("");
			etusername.setText("");
			builder.dismiss();
		}
	};
	// 事件 ---测试连接
	private Button.OnClickListener test = new Button.OnClickListener()
	{

		public void onClick(View v)
		{
			// TODO Auto-generated method stub
			String iptext = setIP.getText().toString();
			String ip = iptext + "/EcareServer1.3/platform/Login_loginFlag";
			JSONObject res = HTTPGetTool.getTool().get1(ip);
			try
			{
				if (res != null)
				{
					Toast.makeText(Login.this, "连接成功", Toast.LENGTH_SHORT).show();
					// builder.dismiss();
				}
				else
				{
					Toast.makeText(Login.this, "连接失败", Toast.LENGTH_SHORT).show();
				}
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};
	// 事件 ---取消
	private Button.OnClickListener cancel = new Button.OnClickListener()
	{

		public void onClick(View v)
		{
			// TODO Auto-generated method stub
			builder.dismiss();
		}
	};

	// // 初始化保存的用户列表
	// private void initHistoryList() {
	// LayoutInflater mLayoutInflater = (LayoutInflater) Login.this
	// .getSystemService(LAYOUT_INFLATER_SERVICE);
	// LinearLayout layout = (LinearLayout) mLayoutInflater.inflate(
	// R.layout.username_history, null);
	// int count = readHistory();
	// Resources resources = getResources();
	// float with = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
	// 200, resources.getDisplayMetrics());
	// float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
	// 50, resources.getDisplayMetrics());
	// for (int i = 0; i < count; i++) {
	// final TextView text = new TextView(Login.this);
	// text.setWidth(Math.round(with));
	// text.setHeight(Math.round(height));
	// text.setTextColor(Color.BLACK);
	// text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
	// text.setText(history[i]);
	// text.setOnClickListener(new View.OnClickListener() {
	//
	// public void onClick(View v) {
	// etusername.setText(text.getText());
	// etusername.setSelection(etusername.length());
	// etpassword.setText("");
	// popup.dismiss();
	// }
	// });
	// layout.addView(text);
	// }
	// popup = new PopupWindow(layout, LayoutParams.WRAP_CONTENT,
	// LayoutParams.WRAP_CONTENT);
	// popup.update();
	// }

	// // 读取历史账号
	// private int readHistory() {
	// SharedPreferences sharedPreferences = getSharedPreferences(
	// "mobile_ecare", 0);
	// history[0] = sharedPreferences.getString("history1", "");
	// history[1] = sharedPreferences.getString("history2", "");
	// history[2] = sharedPreferences.getString("history3", "");
	// history[3] = sharedPreferences.getString("history4", "");
	// history[4] = sharedPreferences.getString("history5", "");
	// int res = 0;
	// for (int i = 0; i < 5; i++) {
	// if (!history[res].equals("")) {
	// res++;
	// } else
	// break;
	// }
	// return res;
	// }

	// 判断输入的用户名是否在历史记录中
	// private boolean isInHistory(String name) {
	// for (int i = 0; i < 5; i++) {
	// if (name.equals(history[i]))
	// return true;
	// }
	// return false;
	// }

	// 新增用户名
	// private void addNewUserName(String name) {
	// int i = 0;
	// for (i = 0; i < 5; i++) {
	// if (history[i].equals("") || i == 4) {
	// break;
	// }
	// }
	// for (int j = 1; j <= i; j++) {
	// history[j - 1] = history[j];
	// }
	// history[i] = name;
	// saveHistory();
	// }

	// 保存账号列表
	// private void saveHistory() {
	// SharedPreferences sharedPreferences = getSharedPreferences(
	// "mobile_ecare", 0);
	// Editor edit = sharedPreferences.edit();
	// edit.putString("history1", history[0]);
	// edit.putString("history2", history[1]);
	// edit.putString("history3", history[2]);
	// edit.putString("history4", history[3]);
	// edit.putString("history5", history[4]);
	// edit.commit();
	// }

	// 将用户名和密码增加到偏好设置中
	// public void setPreferences(String username, String password) {
	// SharedPreferences sharedPreferences = getSharedPreferences(
	// "mobile_ecare", MODE_PRIVATE);
	// Editor edit = sharedPreferences.edit();
	// edit.putString("username", username);
	// edit.putString("password", password);
	// edit.putBoolean("issave", true);
	// if (cbautologin.isChecked()) {
	// edit.putBoolean("isauto", true);
	// } else {
	// edit.putBoolean("isauto", false);
	// }
	// edit.commit();
	// }

	// public void clearPreferences() {
	// SharedPreferences sharedPreferences = getSharedPreferences(
	// "mobile_ecare", 0);
	// Editor edit = sharedPreferences.edit();
	// edit.putString("username", "");
	// edit.putString("password", "");
	// edit.putBoolean("issave", false);
	// edit.putBoolean("isauto", false);
	// edit.commit();
	// }

	// 设置URLUtils.HOST
	private void setHost()
	{
		SharedPreferences sp = this.getSharedPreferences("mobile_ecare", MODE_PRIVATE);
		String host = sp.getString("host", "");
		if (host.equals(""))
		{}
		else
		{
			URLUtils.HOSTMAIN = host;
		}
	}

	// 返回键监听
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
		{
			dialog();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	// 点返回退出应用程序时弹出的提示框
	private void dialog()
	{

		LayoutInflater layoutInflater = LayoutInflater.from(this);
		final View view = layoutInflater.inflate(R.layout.dialog, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		outdialog = builder.create();
		outdialog.setView(view);
		outdialog.setCanceledOnTouchOutside(false);
		outdialog.show();
		outdialog.getWindow().setContentView(R.layout.dialog);

		Window mWindow = outdialog.getWindow();
		WindowManager.LayoutParams lp = mWindow.getAttributes();
		lp.width = (int) (windowwidth * 4 / 5); // 设置宽度
		mWindow.setAttributes(lp);

		left = (Button) outdialog.findViewById(R.id.left);
		left.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				outdialog.dismiss();
				updateManager.closeNotification();
				new Notifier(oThis).closeNotification();
				myApplication.exit();
			}
		});

		right = (Button) outdialog.findViewById(R.id.right);
		right.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				outdialog.dismiss();
				// MainActivity.this.finish();

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		menu.add(0, Menu.FIRST, 0, "检查更新");
		menu.add(0, Menu.FIRST + 1, 0, "退出");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onOptionsItemSelected(item);
		switch (item.getItemId())
		{
			case 1:
				updateManager = new UpdateManager(Login.this);
				// 检查软件更新
				updateManager.checkUpdate(1);
				break;
			case 2:
				android.os.Process.killProcess(android.os.Process.myPid());
				break;
		}
		return true;

	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN)
		{
			if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null)
			{
				manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		tv.setTextColor(getResources().getColor(R.color.test_color_register));
		registertv.setTextColor(getResources().getColor(R.color.test_color_register));
	}
}
